<script setup lang="ts">
import { inject, onBeforeMount, reactive, ref, provide, onUnmounted, onUpdated, onMounted } from 'vue';
import { useStore } from '../../stores/index';
import { storeToRefs } from 'pinia';
import { useRouter } from 'vue-router';
import { SocialInfo, switchPersonCenterShowKey, FollowDto, popMessageKey, popMessage, MusicList, User as u, Music, PostDto, PageInfo } from '@/type';
import {
    getFollowInfo, checkFollow, getPublicUserInfo, getSocialInfo,
    unFollow, follow, getFansInfo, getCollectMusicList, getWeekPlayTimes, getUserCreateMusicList,
    getMyPostList, getOnePost, getAllplayNums
} from '@api';
import Post from '@components/post/Post.vue';
import CommonPagenation from '@components/Common/CommonPagenation.vue';
const popMessage = inject(popMessageKey) as popMessage
/**
 * 此处type用于展示个人中心中不同的页面
 *  1、听歌信息
 */
const props = defineProps(['userId', 'type'])
const store = useStore();
const router = useRouter()



const Active = storeToRefs(store).activeTop
const isEdit = ref(false)
const switchEdit = () => {
    isEdit.value = !isEdit.value
}
let showUserId = "0";
const isUserCenter = ref(true)
const userInfo = storeToRefs(store).getUserInfo;
const showSocialInfo = reactive<SocialInfo>({ concerns: 0, fans: 0, post: 0 })
/**
 * 用户创建的歌单
 */
const userMusicList = ref<MusicList[]>([])
/**
 * 用户收藏的歌单
 */
const userCollectionList = ref<MusicList[]>([])
const BASEURL = store.getBaseUrl()
const showInfo = reactive({ id: '', name: '', avatar: '', introduce: '' })
/**
 * 获取的播放信息
 */
const playCountList = ref<{ music: Music, user: u, count: number }[]>()
/**
 * 最近一周总播放数
 */
const playCount = ref(0);
const allPlayCount = ref(0);
const viewType = ref<'default' | 'posts' | 'follow' | 'fans'>('default')
const postInfoList = ref<PageInfo<PostDto>>()
const followInfoList = ref<FollowDto[]>([])
const fansInfoList = ref<FollowDto[]>([])
/**
 * 当进入其他人的主页时显示关注
 */
const isFollow = ref(false)
/**
 * 头部个人信息的获取
 */
const currentPage = ref(1)
const pageSize = ref(10)
const getAllPlays = () => {
    getAllplayNums(props.userId).then((res) => {
        if (res.data.code == 1) {
            allPlayCount.value = res.data.data
        }
    })
}
const getMyPost = () => {
    getMyPostList(currentPage.value, pageSize.value, props.userId).then(res => {
        if (res.data.code == 1) {
            postInfoList.value = res.data.data
            showSocialInfo.post = res.data.data.total
        }
    })
}

// 更新单个动态
const updatePost = (id: string) => {
    getOnePost(id).then((res) => {
        if (postInfoList.value === undefined) return
        for (let i = 0; i < postInfoList.value.list.length; i++) {
            if (postInfoList.value.list[i].id === id) {
                postInfoList.value.list[i] = res.data.data
                break
            }
        }
    })
}
// 显示评论
const switchShow = (index: number) => {
    // isShow.value = !isShow.value;
    if (postInfoList.value === undefined) return
    postInfoList.value.list[index].showComment = !postInfoList.value?.list[index].showComment
}

const lastPage = () => {
    if (postInfoList.value === undefined) return
    if (postInfoList.value.hasPreviousPage) {
        currentPage.value--
        getMyPost()
    } else {
        popMessage('已经是第一页了喵~', 'info')
    }
}
const changePage = (page: number | 'next' | 'last') => {
    switch (page) {
        case 'next':
            nextPage()
            break
        case 'last':
            lastPage()
            break
        default:
            currentPage.value = page
            getMyPost()
            break
    }
}
const nextPage = () => {
    if (postInfoList.value === undefined) return
    if (postInfoList.value.hasNextPage) {
        currentPage.value++
        getMyPost()
    } else {
        popMessage('已经是最后一页了喵~', 'info')
    }

}



const getData = () => {
    getMyPost()
    getAllPlays()
    getFollowInfo(props.userId, 1).then((res) => {
        followInfoList.value = res.data.data.list
    })
    getFansInfo(props.userId, 1).then(res => {
        if (res.data.code == 1) {
            fansInfoList.value = res.data.data.list;
        }
    })
    getCollectMusicList(props.userId).then(res => {
        if (res.data.code == 1) {
            if (res.data.data != null) {
                userCollectionList.value = res.data.data
            } else {
                userCollectionList.value = []
            }
        }
    })
    getWeekPlayTimes(props.userId).then(res => {
        if (res.data.code == 1) {
            if (playCountList != undefined) {
                playCountList.value = res.data.data
                if (playCountList.value == undefined) {
                    playCount.value = 0
                    playCountList.value = []
                    return
                }
                for (let play of playCountList.value) {
                    playCount.value += play.count
                }
            }
        }
    })
    // 用户进入自己的主页需要获取的独特信息
    if (userInfo.value.id === props.userId) {
        isUserCenter.value = true
        userMusicList.value = store.getMyMusicList
        showInfo.avatar = store.getUserAvatar
        getSocialInfo(props.userId).then(res => {
            if (res.data.code === 1) {
                showSocialInfo.concerns = res.data.data.concerns;
                showSocialInfo.fans = res.data.data.fans;

                store.setSocialInfo(showSocialInfo);
                showInfo.id = userInfo.value.id
                showInfo.name = userInfo.value.name
                showInfo.avatar = userInfo.value.avatar
                showInfo.introduce = userInfo.value.introduce as string
            }
        })
        // 用户进入其他用户的页面
    } else {
        isUserCenter.value = false
        getIsFollow(props.userId)
        getUserCreateMusicList(props.userId).then((res) => {
            console.log("获取到歌单", res.data.data);
            userMusicList.value = res.data.data
        })
        getPublicUserInfo(props.userId).then(res => {
            if (res.data.code == 1) {
                showInfo.id = res.data.data.id;
                showInfo.name = res.data.data.name;
                showInfo.avatar = res.data.data.avatar
                showInfo.introduce = res.data.data.introduce;
            }
        })
        getSocialInfo(props.userId).then(res => {
            if (res.data.code === 1) {
                showSocialInfo.concerns = res.data.data.concerns;
                showSocialInfo.fans = res.data.data.fans;

            }
        })
    }
    showUserId = props.userId
}
/**
 * 当进入其他用户界面时，检查是否关注
 * @param userId 用户id
 */
const getIsFollow = (userId: string) => {
    checkFollow(userId).then((res) => {
        if (res.data.code === 1) {
            isFollow.value = Boolean(res.data.data);
        }
    })
}
onBeforeMount(() => {
    console.log(`类型${props.type}`);
    Active.value.active = false
    switch (props.type) {
        case 'center':
            viewType.value = 'default'
            break
        case 'posts':
            viewType.value = 'posts'
            break
        case 'follow':
            viewType.value = 'follow'
            break
        case 'fans':
            viewType.value = 'fans'
            break
    }
    getData()
})
onMounted(() => {
    showUserId = props.userId;
})
onUnmounted(() => {
    console.log("卸载");
})
// 从其他人页面点击个人中心时刷新数据
onUpdated(() => {
    console.log(`当前type:${props.type}`);
    console.log("当前条件", props.userId !== showUserId)
    if (userInfo.value.id === showUserId) {
        isUserCenter.value = true
    }
    if (props.userId !== showUserId) {
        getData()
        viewType.value = props.type
    } else {
        if (props.userId === store.UserInfo.id) {
            showInfo.name = store.UserInfo.name
            showInfo.introduce = store.UserInfo.introduce as string
        }
    }
    showUserId = props.userId
})
const toEditUserInfo = () => {
    isEdit.value = true;
    router.push({
        name: 'editPersonInfo',
    })
}
const toMusicListPage = (id: number | string) => {
    router.push({
        name: 'musicList',
        params: {
            musicListId: id,
            disableSlide: 0
        }
    })
}
const switchSocialInfo = (type: 'default' | 'posts' | 'follow' | 'fans') => {
    viewType.value = type;
}
const followUser = () => {
    if (store.isLogin != 1) {
        popMessage("未登陆", 'error')
        return
    }
    follow(props.userId).then(res => {
        if (res.data.code == 1) {
            isFollow.value = true;
            popMessage('关注成功', 'success')
        }
    })
}
const unFollowUse = () => {
    if (store.isLogin != 1) {
        popMessage("未登陆", 'error')
        return
    }
    unFollow(props.userId).then(res => {
        if (res.data.code == 1) {
            isFollow.value = false;
            popMessage('取关成功', 'success')
        }
    })
}

const toUserPage = (userId: string, type: 'default' | 'posts' | 'follow' | 'fans') => {
    router.push({
        name: 'personCenter', params: {
            userId: userId,
            type
        }
    })
}
const toMusicPage = (musicId: string) => {
    router.push({
        name: 'singleMusic',
        params: { musicId }
    })
}

provide(switchPersonCenterShowKey, switchEdit);
</script>
<template>
    <template v-if="!isEdit">
        <div class="container">
            <div class="userInfo">
                <div class="avatar">
                    <img :src="BASEURL + '/static/image/' + showInfo.avatar" alt="">
                </div>
                <div class="detail">
                    <div class="top">
                        <p @click="viewType = 'default'" class="userName">{{ showInfo.name }}</p>
                        <button v-if="isUserCenter" class="edit" @click="toEditUserInfo">编辑个人资料</button>
                        <template v-else>
                            <button v-if="!isFollow" class="follow" @click="followUser">关注</button>
                            <button v-else class="follow" @click="unFollowUse">取消关注</button>
                        </template>
                    </div>
                    <div class="active">
                        <div class="item" @click="switchSocialInfo('posts')">
                            <span class="num">{{ showSocialInfo.post }}</span>
                            <span class="type">动态</span>
                        </div>
                        <div class="item" @click="switchSocialInfo('follow')">
                            <span class="num">{{ showSocialInfo.concerns }}</span>
                            <span class="type">关注</span>
                        </div>
                        <div class="item" @click="switchSocialInfo('fans')">
                            <span class="num">{{ showSocialInfo.fans }}</span>
                            <span class="type">粉丝</span>
                        </div>
                    </div>
                    <div class="intro">
                        <span>个人简介:{{ showInfo.introduce }}</span>
                    </div>
                </div>
            </div>
            <div class="listenRank" v-show="playCountList && playCountList.length > 0 && viewType == 'default'">
                <div class="title">
                    <div class="left">
                        <h2 class="text">听歌排行</h2>
                        <p class="plays">累计听歌:{{ allPlayCount }}首</p>
                    </div>
                    <div class="right">
                        <p class="week">最近一周:{{ playCount }}</p>
                        <p>所有时间:{{ allPlayCount }}</p>
                    </div>
                </div>
                <div class="rank" v-show="viewType == 'default'">
                    <ul>
                        <li class="item" v-for="play, index of playCountList">
                            <div class="musicInfo">
                                <p class="index">{{ index + 1 }}.</p>
                                <img @click="toMusicPage(play.music.musicId)" src="../../assets/play.svg" alt="">
                                <p @click="toMusicPage(play.music.musicId)" class="musicTitle">{{ play.music.title }}</p>
                                <p class="singer">-{{ play.user.name }}</p>
                            </div>
                            <!-- 播放量百分比 -->
                            <div :style="{ width: ((316 - 65) * (play.count / playCount)) + 65 + 'px' }" class="rankInfo">

                            </div>
                            <span class="rankData">{{ play.count }}次</span>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="musicList" v-show="viewType == 'default' && userMusicList.length > 0">
                <div class="title">
                    <h2>{{ (isUserCenter ? '我' : '他') + `创建的歌单(${userMusicList.length})` }}</h2>
                </div>
                <div class="list">
                    <div class="music" v-for="list of userMusicList" @click="toMusicListPage(list.id as string)">
                        <img :src="BASEURL + '/static/image/' + list.image" alt="">
                        <div class="Musictitle">
                            {{ list.title }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="musicList" v-show="viewType == 'default' && userCollectionList.length > 0">
                <div class="title">
                    <h2>{{ (isUserCenter ? '我' : '他') + `收藏的歌单(${userCollectionList.length})` }}</h2>
                </div>
                <div class="list">
                    <div class="music" v-for="list of userCollectionList" @click="toMusicListPage(list.id as string)">
                        <img :src="BASEURL + '/static/image/' + list.image">
                        <div class="Musictitle">
                            {{ list.title }}
                        </div>
                    </div>
                </div>
            </div>
            <div class="post" v-show="viewType == 'posts'">
                <div class="title">
                    <h2 class="text">动态 ({{ postInfoList?.total }})</h2>
                </div>
                <div class="list" v-if="postInfoList !== undefined">
                    <Post :post-list="postInfoList.list !== undefined ? postInfoList.list : []" :switch-show="switchShow"
                        :update-post="updatePost" />
                    <CommonPagenation :page-info="postInfoList" :change-page="changePage" :current-page="currentPage" />
                </div>
                <template v-if="postInfoList?.total == 0">
                    <div class="noFollow">
                        <span class="tips">还没有动态</span>
                    </div>
                </template>
            </div>
            <div class="follow" v-show="viewType == 'follow'">
                <div class="title">
                    <h2 class="text">关注 ({{ followInfoList.length }})</h2>
                </div>
                <div class="list">
                    <div class="followContainer" v-for="follow of followInfoList">
                        <img @click="toUserPage(follow.user.id, 'default')"
                            :src="BASEURL + '/static/image/' + follow.user.avatar" class="avatar">
                        <div class="followInfo">
                            <span @click="toUserPage(follow.user.id, 'default')" class="name">{{ follow.user.name }}</span>
                            <div class="socialInfo">
                                <span @click="toUserPage(follow.user.id, 'posts')">动态</span>
                                <span @click="toUserPage(follow.user.id, 'posts')">{{ follow.socialInfo.post }}</span>
                                <span @click="toUserPage(follow.user.id, 'follow')">关注</span>
                                <span @click="toUserPage(follow.user.id, 'follow')">{{ follow.socialInfo.concerns }}</span>
                                <span @click="toUserPage(follow.user.id, 'fans')">粉丝</span>
                                <span @click="toUserPage(follow.user.id, 'fans')">{{ follow.socialInfo.fans }}</span>
                            </div>
                            <span class="introduce">{{ follow.user.introduce }}</span>
                        </div>
                    </div>
                </div>
                <template v-if="followInfoList.length == 0">
                    <div class="noFollow">
                        <span class="tips">还没有关注人</span>
                    </div>
                </template>
            </div>
            <div class="follow" v-show="viewType == 'fans'">
                <div class="title">
                    <h2 class="text">粉丝 ({{ fansInfoList.length }})</h2>
                </div>
                <div class="list">
                    <div class="followContainer" v-for="fan of fansInfoList">
                        <img :src="BASEURL + '/static/image/' + fan.user.avatar" class="avatar">
                        <div class="followInfo">
                            <span @click="toUserPage(fan.user.id, 'default')" class="name">{{ fan.user.name }}</span>
                            <div class="socialInfo">
                                <span @click="toUserPage(fan.user.id, 'posts')">动态</span>
                                <span @click="toUserPage(fan.user.id, 'posts')">{{ fan.socialInfo.post }}</span>
                                <span @click="toUserPage(fan.user.id, 'follow')">关注</span>
                                <span @click="toUserPage(fan.user.id, 'follow')">{{ fan.socialInfo.concerns }}</span>
                                <span @click="toUserPage(fan.user.id, 'fans')">粉丝</span>
                                <span @click="toUserPage(fan.user.id, 'fans')">{{ fan.socialInfo.fans }}</span>
                            </div>
                            <span class="introduce">{{ fan.user.introduce }}</span>
                        </div>
                    </div>
                </div>
                <template v-if="fansInfoList.length == 0">
                    <div class="noFans">
                        <span class="tips">还没有粉丝</span>
                    </div>
                </template>
            </div>

        </div>
    </template>
    <RouterView name="EditPersonInfo" />
</template>
<style lang="css" scoped>
.musicList .list {
    justify-content: space-between;
}

.rankData {
    position: absolute;
    right: 260px;
    top: 0px;
    height: 100%;
    line-height: 40px;
    font-size: 14px;
    color: #999;
}

.rankInfo {
    position: absolute;
    left: 550px;
    top: 0px;
    height: 100%;
    background-color: var(--blue-style);
    opacity: 0.1;
    max-width: 316px;
}

.tips {
    font-size: 25px;
}

.noFans,
.noFollow {
    height: 400px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: 700;
}

.followInfo .introduce {
    font-size: 12px;
    margin-top: 5px;
}

.socialInfo span:nth-child(2n) {
    border-right: 1px solid #999;
    margin-right: 4px;
    padding-right: 4px;
    color: var(--blue-style);
}

.socialInfo span:last-child {
    border-right: none;
}

.socialInfo span:nth-child(2n + 1) {
    margin-right: 2px;
}

.socialInfo span {
    font-size: 10px;
}

.socialInfo {
    cursor: pointer;
}

.followInfo .name {
    font-size: 14px;
    margin-bottom: 4px;
    color: var(--blue-style);
    cursor: pointer;
}

.followInfo .name:hover {
    text-decoration: underline;
}

.followInfo {
    display: flex;
    flex-direction: column;
}

.followContainer:last-child,
.followContainer:nth-last-child(2) {
    border-bottom: 1px solid #d5d5d5;
}

.followContainer:nth-child(4n),
.followContainer:nth-child(4n-1) {
    background-color: #FAFAFA;
}

.followContainer:nth-child(2n+1) {
    border-right: 1px solid #d5d5d5;
}

.followContainer {
    display: flex;
    padding: 20px 20px;
}

.follow .list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    border-left: 1px solid #d5d5d5;
    border-right: 1px solid #d5d5d5;
}

.follow .list .avatar {
    height: 60px;
    width: 60px;
    margin-right: 15px;
    cursor: pointer;
}

.post .text,
.follow .text {
    font-size: 20px;
    margin: 0;
}

.list .Musictitle {
    font-size: 14px;
}

.musicList .list {
    display: grid;
    margin-top: 20px;
    grid-template-columns: repeat(5, 162px);
}

.list .music {
    margin-bottom: 20px;
    cursor: pointer;
    width: 140px;
}

.list .music img {
    height: var(--music-list-img-size);
    width: var(--music-list-img-size);
}

.musicList h2 {
    font-weight: normal;
    margin: 0;
}

.musicInfo {
    display: flex;
    align-items: center;
}

.musicInfo .singer {
    font-size: 12px;
    color: #aeaeae;
}

.musicInfo .musicTitle {
    margin-left: 10px;
    font-size: 12px;
    font-weight: 800;
    cursor: pointer;
}

.musicInfo .index {
    width: 30px;
    text-align: right;
}

.musicInfo p {
    margin: 0;
    margin-right: 10px;
    height: 40px;
    line-height: 40px;
}

.musicInfo img {
    height: 15px;
    width: 15px;
    color: #666;
}

.rank ul {
    padding-left: 0;
    margin-top: 0;
    border-left: 1px solid #e5e5e5;
    border-right: 1px solid #e5e5e5;
    border-bottom: 1px solid #e5e5e5;
}

.rank .item:nth-child(n) {
    background-color: #fff;
}

.rank .item:nth-child(2n) {
    background-color: #f7f7f7;
}

.rank .item {
    list-style: none;
    position: relative;
}

.listenRank .title .right .week {
    margin-right: 10px;
}

.listenRank .title .right {
    display: flex;
    justify-content: baseline;
    font-size: 12px;
}

.listenRank .title .left .text,
.listenRank .title .left .plays,
.listenRank .title .right p {
    margin: 0;
}

.listenRank .title .left {
    display: flex;
    align-items: baseline;
}

.listenRank {
    margin-top: 40px;
}

.listenRank .plays {
    font-size: 12px;
    color: #666;
    margin-left: 10px !important;
}

.follow .title,
.listenRank .title .text {
    font-size: 22px;
    color: #666;
    font-weight: normal;
}

/* 通用title样式 */
.post .title,
.musicList .title,
.listenRank .title,
.follow .title {
    display: flex;
    padding-bottom: 10px;
    align-items: flex-end;
    justify-content: space-between;
    border-bottom: 2px solid var(--red-style);
}

.userInfo .avatar img {
    height: var(--avatar-large-size);
    width: var(--avatar-large-size);
}

.userInfo .userName {
    font-size: 22px;
    margin-top: 5px;
    margin-bottom: 20px;
    cursor: pointer;
}

.active,
.intro {
    color: #666;
}

.active .item {
    cursor: pointer;
}

.active {
    display: flex;
    margin-top: 10px;
}

.intro {
    margin-top: 20px;
    font-size: 12px;
}

.detail .item .type {
    font-size: 12px;
}

.detail .item .num {
    font-size: 24px;
}

.detail .item {
    display: flex;
    flex-direction: column;
    margin-right: 40px;
    height: 50px;
    vertical-align: middle;
    align-items: center;
    justify-content: space-around;

}

.detail .item:nth-child(-n+2) {
    padding-right: 40px;
    border-right: 1px #ccc solid;
}

.detail .top {
    display: flex;
    width: 100%;
    justify-content: space-between;
    border-bottom: 1px solid #ccc;
}

.detail .edit {
    font-size: 12px;
    height: 30px;
    width: 110px;
    background-color: #F8F8F8;
    border-radius: 3px;
}

.top .follow {
    font-size: 12px;
    height: 30px;
    width: 80px;
    background-color: #F8F8F8;
    border-radius: 3px;
    cursor: pointer;
}

.userInfo .detail {
    margin-left: 40px;
    width: 100%;
}

.userInfo {
    display: flex;
    margin-bottom: 20px;
}

.container {
    padding: 40px;
}
</style>